package sd.settemmezzo.player;

import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

import sd.settemmezzo.common.PlayerInterface;
import sd.settemmezzo.common.Registration;


public class Player extends UnicastRemoteObject implements PlayerInterface {

	private static final long serialVersionUID = -7362094494588588330L;
	
	private String name;
	private String ip;
	private int id;
	
	private Vector<PlayerInterface> playersList;
	
	public Player() throws RemoteException {
		super();
	}
	
	public Player(String name, String ip) throws RemoteException {
		super();
		this.name = name;
		this.ip = ip;
	}
	
	public int getId() {
		return id;
	}
	
	public void setId(int id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}

	public String getIp() {
		return ip;
	}
	
	public static void main(String[] args) {
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        
        PlayerInterface player = null;
        
        /* Register client interface */
        String rmiName = "//localhost/" + args[0];
        try {
            player = new Player(args[0], InetAddress.getLocalHost().getHostName());
            Naming.rebind(rmiName, player);
            System.out.println("[Client: " + args[0] + "] Bound.");
        } catch (Exception e) {
            System.err.println("Player exception: " + e.getMessage());
            e.printStackTrace();
        }
        
        /* Get RegistrationServer remote interface from RMIRegistry  */
        try {
            Registry registry = LocateRegistry.getRegistry();
            Registration registration = (Registration) registry.lookup("Registration");
            player.setId(registration.register(player));
            System.out.println("My ID = " + player.getId());
        } catch (Exception e) {
            System.err.println("Player exception:");
            e.printStackTrace();
        }
    }

	public void setPlayersList(Vector<PlayerInterface> playersList) throws RemoteException {
		this.playersList = playersList;
		System.out.print("Players list received: ");
		for (PlayerInterface player : playersList) {
			System.out.print(player.getId() + ":" + player.getName() + " (" + player.getIp() + ") ");
		}
		System.out.println("");
		
		/* Create the Ring */
		if (this.id == 2) {
			PlayerInterface nodo3 = (PlayerInterface) playersList.get(2);
			System.out.println("ID NODO3 = " + nodo3.getId());
		}
	}
	
}
